package mystia.lorelei.app.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import mystia.lorelei.app.entity.Cuisine;
import mystia.lorelei.app.entity.dto.CuisineDTO;
import mystia.lorelei.app.service.CuisineService;
import mystia.lorelei.app.util.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;


@RestController
@RequestMapping("/cuisine")
@Tag(name = "菜品管理")
public class CuisineController {
    @Resource
    private CuisineService cuisineService;

    @GetMapping("/list")
    @Operation(summary = "菜品列表")
    public Result<List<CuisineDTO>> listCuisines() {
        List<Cuisine> cuisines = cuisineService.listCuisines();
        List<CuisineDTO> cuisineDTOs = new ArrayList<>();
        // 将Cuisine对象转成CuisineDTO对象，并插入到返回结果集中
        cuisines.forEach(cuisine -> {
            CuisineDTO cuisineDTO = new CuisineDTO(cuisine.name,cuisine.price,cuisine.description,null);
            // 字节数组转Base64
            String base64 = Base64.getEncoder().encodeToString(cuisine.image);
            cuisineDTO.imgBase64 = "data:"+cuisine.imageType+";base64,"+base64;
            cuisineDTOs.add(cuisineDTO);
        });
        return Result.ok(cuisineDTOs);
    }
    @GetMapping("/listPro")
    @Operation(summary = "列出菜品(带ID)")
    public Result<List<Cuisine>> listCuisinesPro() {
        List<Cuisine> cuisines = cuisineService.listCuisines();
        return Result.ok(cuisines);
    }

    @PostMapping("/save")
    @Operation(summary = "保存/更新菜品")
    public Result<Object> saveCuisine(@RequestParam("image") MultipartFile image,
                            @RequestParam("name") String name,
                            @RequestParam("description") String description,
                            @RequestParam("price") BigDecimal price) throws IOException {
        Cuisine cuisine = new Cuisine(null,name,price,description,image.getBytes(),image.getContentType());
        cuisineService.saveCuisine(cuisine);
        return Result.ok();
    }
    
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除菜品")
    public Result deleteCuisine(@PathVariable("id") int id){
        cuisineService.deleteCuisine(id);
        return Result.ok();
    }
    
    @DeleteMapping("/delete")
    @Operation(summary = "批量删除")
    public Result deleteCuisines(@RequestBody List<Integer> ids){
        try{
            cuisineService.deleteCuisines(ids);
            return Result.ok();
        }catch (Exception e){
            return Result.fail();
        }
    }
    
    
    @PostMapping("/image")
    public void imageSender(@RequestBody MultipartFile image, HttpServletRequest request) throws IOException {
        // 空方法
    }
    
}
